package dao

import (
	"hsy/server/framework"
	"hsy/server/model"
	"log"
)

//CategoryDao ...
type CategoryDao struct {
}

/*Add ...*/
func (cd *CategoryDao) Add(c *model.Category) int64 {
	key := "(category_name,category_desc,create_by,update_by,p_id,created_time,updated_time)"

	result, err := framework.DB.Exec("INSERT INTO hsy_category "+key+" VALUES (?,?,?,?,?,?,?)",
		c.CategoryName,
		c.CategoryDesc,
		c.CreatedBy,
		c.UpdatedBy,
		c.CreatedTime,
		c.UpdatedTime)
	if err != nil {
		log.Panic("insert the category is faild")
		return 0
	}
	id, err := result.LastInsertId()
	if err != nil {
		log.Panic("insert the category is faild")
		return 0
	}
	return id

}

//FindByID ...
func FindByID(id int) (model.Category, error) {

	var category model.Category
	where := "where id=" + string(id)
	categorys, err := FindAll(where)
	if err != nil {
		return category, err
	}

	return categorys[0], nil
}

//FindAll ...
func FindAll(where string) ([]model.Category, error) {
	query := "SELECT * FROM hsy_category"
	if where != "" {
		query += " " + where
	}
	rows, err := framework.DB.Query(query)

	if err != nil {
		return nil, err
	}

	defer rows.Close()
	var categorys []model.Category

	for rows.Next() {
		var category model.Category
		err := rows.Scan(&category.ID, &category.CategoryName, &category.CategoryDesc)
		if err != nil {
			return nil, err
		}
		categorys = append(categorys, category)
	}

	return categorys, nil
}

//FindAllByPId ...
func FindAllByPId(pID int) ([]model.Category, error) {
	where := "where pId=" + string(pID)
	return FindAll(where)
}
